import { Injectable } from '@angular/core';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzMessageService } from 'ng-zorro-antd/message';
import { LocalizationService } from '@abp/ng.core';
import { EntityConfig } from './entity-config.types';
import * as XLSX from 'xlsx';

export interface ExportExcelOptions {
  title?: string;
  content?: string;
  okText?: string;
  cancelText?: string;
  noDataMessage?: string;
  fileName?: string;
}

@Injectable({
  providedIn: 'root'
})
export class ExportExcelService {

  constructor(
    private modalService: NzModalService,
    private message: NzMessageService,
    private localizationService: LocalizationService
  ) {}

  /**
   * 导出Excel文件
   * @param data 要导出的数据数组
   * @param entityConfig 实体配置
   * @param menuKey 菜单多语言键
   * @param options 导出选项
   */
  exportExcel<T>(
    data: T[], 
    entityConfig: EntityConfig, 
    menuKey: string,
    options: ExportExcelOptions = {}
  ): void {
    if (!data || data.length === 0) {
      const noDataMessage = options.noDataMessage || 'BasicArchives::UI:ExportDialog.Message.NoData';
      this.message.warning(this.l(noDataMessage));
      return;
    }

    const defaultOptions: ExportExcelOptions = {
      title: 'BasicArchives::UI:ExportDialog.Title',
      content: 'BasicArchives::UI:ExportDialog.Content',
      okText: 'BasicArchives::UI:ExportDialog.OK',
      cancelText: 'BasicArchives::UI:ExportDialog.Cancel',
      fileName: `${this.l(menuKey)}_${new Date().toISOString().split('T')[0]}.xlsx`
    };

    const finalOptions = { ...defaultOptions, ...options };

    this.modalService.confirm({
      nzTitle: this.l(finalOptions.title),
      nzContent: this.l(finalOptions.content),
      nzOkText: this.l(finalOptions.okText),
      nzCancelText: this.l(finalOptions.cancelText),
      nzOnOk: () => {
        this.generateExcelFile(data, entityConfig, menuKey, finalOptions.fileName);
      }
    });
  }

  /**
   * 生成Excel文件
   * @param data 数据
   * @param entityConfig 实体配置
   * @param menuKey 菜单键
   * @param fileName 文件名
   */
  private generateExcelFile<T>(
    data: T[], 
    entityConfig: EntityConfig, 
    menuKey: string,
    fileName: string
  ): void {
    const visibleColumns = entityConfig.propertys.filter(prop => prop.show);

    const exportData = data.map(item => {
      const rowData = {};
      visibleColumns.forEach(prop => {
        const columnName = this.l(`BasicArchives::ModelTitle:${entityConfig.entityType}.${prop.name}`);
        rowData[columnName] = prop.field(item);
      });
      return rowData;
    });

    const worksheet = XLSX.utils.json_to_sheet(exportData);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, this.l(menuKey));

    XLSX.writeFile(workbook, fileName);
  }

  /**
   * 本地化方法
   * @param key 多语言键
   * @param params 参数
   */
  private l(key: string, ...params: string[]): string {
    return this.localizationService.instant(key, ...params);
  }
}